package com.ztc.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.baidu.ueditor.ConfigManager;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.upload.StorageManager;

/**
 * 上传文件工具类
 * @author libo
 */
public class UploadUtil {
    
	/**
     * 上传文件
     * 绝对路径上传
     * @param file 文件
     * @param request
     * @param rootPath 根路径
     * @param actionType action类型
     * @return
     */
    public static State upload(MultipartFile file, HttpServletRequest request, String rootPath, String actionType){
        ConfigManager configManager = ConfigManager.getInstance( rootPath, request.getContextPath(), request.getRequestURI() );
        int actionCode = ActionMap.getType( actionType );
        Map<String, Object> conf = null;
		try {
			conf = configManager.getConfig( actionCode );
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        String savePath = (String) conf.get("savePath");
		String originFileName = file.getOriginalFilename();
		String suffix = FileType.getSuffixByFilename(originFileName);

		originFileName = originFileName.substring(0,
				originFileName.length() - suffix.length());
		savePath = savePath + suffix;

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
			return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		}

		savePath = PathFormat.parse(savePath, originFileName);

		String physicalPath = (String) conf.get("rootPath") + savePath;

		InputStream is;
		try {
			is = file.getInputStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			is.close();

			if (storageState.isSuccess()) {
//				Properties properties = PropertiesUitls.fetchProperties("/config.properties");
//				String imageUrlPrefix = properties.getProperty("server.basepath");
				storageState.putInfo("url", PathFormat.format(savePath)); //imageUrlPrefix + 
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName);
			}
			return storageState;
		} catch (IOException e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}
    }
    
    /**
     * 上传文件
     * ftp上传
     * @param file 文件
     * @param request
     * @param rootPath 根路径
     * @param actionType action类型
     * @return
     */
    public static State uploadByFtp(MultipartFile file, HttpServletRequest request, String rootPath, String actionType){
    	ConfigManager configManager = ConfigManager.getInstance( rootPath, request.getContextPath(), request.getRequestURI() );
        int actionCode = ActionMap.getType( actionType );
        Map<String, Object> conf = null;
		try {
			conf = configManager.getConfig( actionCode );
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String savePath = (String) conf.get("savePath");
		String originFileName = file.getOriginalFilename();
		String suffix = FileType.getSuffixByFilename(originFileName);
		//验证文件后缀
		if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
			return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		}
		//判断文件大小
		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if (file.getSize() > maxSize) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		savePath = savePath + suffix;
		savePath = PathFormat.parse(savePath, originFileName);
		
        boolean success = false;
		try {
			FtpUtil ftp = new FtpUtil();
			success = ftp.uploadFile(savePath, file.getInputStream());
	        if(success) {
	        	State state = new BaseState(true);
	    		state.putInfo("size", file.getSize() );
	    		state.putInfo("title", savePath.substring(savePath.lastIndexOf("/") + 1) );
	    		state.putInfo("url", PathFormat.format(savePath)); //imageUrlPrefix + 
	    		state.putInfo("type", suffix);
	    		state.putInfo("original", originFileName);
	            return state;
	        }
		} catch (IOException e) {
			
		}
		return new BaseState(false, AppInfo.IO_ERROR);
    }
    
    private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
